package pub.tbc.api.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.Headers;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.toolkit.Objs;

/**
 * 针对http请求的特定ContentType过滤
 *
 * @author tbc on 2017/3/1 16:40:17.
 */
@Slf4j
public class ContentTypeFilter extends AbstractHttpInboundHandler<FullHttpRequest> {
    private final String DEFAULT_CONTENT_TYPE = "application/json";

    /**
     * 是否有请求体
     *
     * @param request 请求对象
     * @return boolean
     */
    private boolean isContent(FullHttpRequest request) {
        // get和delete方法无请求体
        String method = request.method().name();

        HttpHeaders headers = request.headers();


        return false;
    }

    private boolean isWhiteContentType(FullHttpRequest msg) {
        HttpHeaders headers = msg.headers();
        String contentType = headers.get(HttpHeaderNames.CONTENT_TYPE);
//        String contentTypeName = contentType.split(";")[0];
//        if (DEFAULT_CONTENT_TYPE.equalsIgnoreCase(contentTypeName)) {
//            return true;
//        }
        return contentType.contains(DEFAULT_CONTENT_TYPE);
    }

    private void next(ChannelHandlerContext ctx, FullHttpRequest request) {
        ctx.fireChannelRead(request);
    }

    /**
     * 判断http请求的contentType是否为
     *
     * @param ctx     ChannelHandlerContext
     * @param request FullHttpRequest
     * @throws Exception .
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        if (Objs.isEmpty(request))
            throw new RuntimeException("请求无效或者解码失败！");

        //
        if (isContent(request)) {
            next(ctx, request);
        }


    }
}
